<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-button type="primary" @click="add">添加角色</el-button>
      <!-- 角色列表 -->

      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <!-- 三级权限 -->
          <template slot-scope="scope">
            <el-row
              :class="['borderBottom', 'vcenter', a1 === 0 ? 'boderTop' : '']"
              v-for="(item1, a1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoles(scope.row.id, item1.id)">
                  >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <!-- 二级 -->
              <el-col :span="19">
                <el-row
                  :class="['vcenter', a2 === 0 ? '' : 'boderTop']"
                  v-for="(item2, a2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRoles(scope.row.id, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRoles(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- 删除 修改 分配权限 -->
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRolesUser(scope.row.id)"
              >删除</el-button
            >
            <!-- 权限分配按钮 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-share"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 权限分配对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="60%"
    >
      <!-- 权限列表内容 -->
      <el-tree
        show-checkbox
        :data="rightsList"
        :props="treeProps"
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <!-- 权限确认 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="setEditUser" width="60%">
      <!-- 编辑角色 -->

      <el-form :model="editUserForm" ref="setEditRef" label-width="80px">
        <el-form-item label="角色名称" prop="">
          <el-input v-model="editUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="">
          <el-input v-model="editUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 编辑确认 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setEditUser = false">取 消</el-button>
        <el-button type="primary" @click="editSubmitRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addUser" width="60%">
      <!--添加角色角色 -->

      <el-form :model="addNewUser" ref="addEditRef" label-width="80px">
        <el-form-item label="角色名称" >
          <el-input v-model="addNewUser.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" >
          <el-input v-model="addNewUser.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加角色确认 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUser = false">取 消</el-button>
        <el-button type="primary" @click="addUserInList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

           
<script>
export default {
  data() {
    return {
      rolesList: [],
      // 控制修改对话框的显示隐藏
      setRightsDialogVisible: false,
      // 保存权限数据
      rightsList: [],
      // 属性控制属性的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 可以在控制台打印数据 找到id 放到数组里面 在点击权限分配 这个数组中的id对应的权限会被选中
      defKeys: [],
      //角色ID
      role: '',
      //编辑角色对话框的显示隐藏
      setEditUser: false,
      //编辑角色对话框的原始内容
      editUserForm: {},
      //添加新角色
      addNewUser: {},
      //控制添加角色对话框
      addUser: false,
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //将获取到的数据 赋值给rolesList
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      //   console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error('用户列表获取失败')

      this.rolesList = res.data
      // console.log(this.getRolesList)
    },
    // 删除角色
    async removeRolesUser(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除角色，确定删除角色吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getRolesList()
      this.$message.success('删除成功！')
    },

    //删除权限
    async removeRoles(id, id1) {
      //弹窗确认
      const confirmResult = await this.$confirm(
        '此操作将永久删除，确定删除吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${id.id}/rights/${id1}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // this.getRolesList()
          id.children=res.data
      this.$message.success('删除成功！')
    },
    //展示分配权限的对话框
    async showSetRightDialog(val) {
      //存储角色id
      this.role = val.id
      //获取所有权限的数据

      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status != 200) {
        return this.$message.error('获取权限数据失败')
      }
      // 数据保存到data 中
      this.rightsList = res.data
      var arr = []
      this.getThreeId(val, arr)
      this.defKeys = arr

      this.setRightsDialogVisible = true
    },
    //递归查找第三级id
    getThreeId(parent, arr) {
      if (!parent.children) {
        return arr.push(parent.id)
      }
      parent.children.forEach((item) => {
        this.getThreeId(item, arr)
      })
    },
    // 分配权限
    async setRights() {
      // const keys = [
      //   ...this.$refs.treeRef.getCheckedKeys(),
      //   ...this.$refs.treeRef.getHalfCheckedKeys()
      // ]
      const keys=[this.$refs.treeRef.getCheckedKeys()]
      keys.push(this.$refs.treeRef.getHalfCheckedKeys())
   
      const str = keys.join(',')
      console.log(str)
      console.log(this.role)
      const { data: res } = await this.$http.post(`roles/${this.role}/rights`, {
        rids: str,
      })

      if (res.meta.status !== 200) {
        return this.$message.error('角色授权失败')
      }

      console.log(res.meta.status)
      this.$message.success('角色授权成功')
      this.getRolesList()
      this.setRightsDialogVisible = false
    },
    //展示编辑角色对话框
    async showEditDialog(id) {
      this.role = id
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(id)
      console.log(res)
      this.editUserForm = res.data
      this.setEditUser = true
    },
    //单击确定将编辑后的值放到数据库
    editSubmitRole() {
      this.$refs.setEditRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.put('roles/' + this.role, {
          roleName: this.editUserForm.roleName,
          roleDesc: this.editUserForm.roleDesc,
        })
        console.log(this.role)
        console.log(res)
        this.getRolesList()
      })

      this.setEditUser = false
    },
    add() {
      this.addUser = true
    },
    //添加角色
    addUserInList() {
      this.$refs.addEditRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.post('roles',this.addNewUser )
             if (res.meta.status != 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏对话框 渲染数据
        this.addUser = false
        this.getRolesList()
      })
    },
  },
}
</script>
<style>
.el-tag {
  margin: 10px;
}
.borderTop {
  border-top: 1px solid#eee;
}
.borderBottom {
  border-bottom: 1px solid#eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>